const Hapi = require("hapi");
const Vision = require('vision');
const Swagger = require("hapi-swagger");
const joi = require("joi")
const bcrypt = require("bcryptjs");
const server = new Hapi.Server({
    host: '172.16.61.103',
    port: 3002,
    routes: {
        files: {
            relativeTo: require("path").join(__dirname, 'public')
        },
    },

})

const init = async () => {
    await server.register(require('inert'));
    await server.register(Vision);
    await server.register({
        plugin: require("hapi-mysql2"),
        options: {
            settings: {
            host: '172.16.61.176',
            user: 'root',
            password: '123456',
            database: 'panda' ,
            port: 3306   
        },
            decorate: true
        }
    })
    await server.register({
        plugin: Swagger,
        options: {
            info: {
                title: 'the api ',
                version: '1.0.0'
            }
        }
    })
    await server.start();
}
process.on('unhandleRejection', err => {
    logger.error("退出")
    process.exit(1);
})
server.route({
    path: '/a',
    method: 'get',
    handler: (request, h) => {
        h.state()
        h.state("cok", "1111111", {
            ttl: 24 * 60 * 60 * 1000,     // One day
        })
        return h.response({ a: 1 }).code(400)
    }
})
server.route({
    path: '/test/{name}',
    method: 'GET',
    config: {
        handler: async (request, h) => {
            let salt = await bcrypt.genSalt(5);

            let { name } = request.params;
            let value = await bcrypt.hash(name, salt);
            return h.response({
                name: value
            })
        },
        validate: {
            params: {
                name: joi.string().required().min(1).description("用户名字")
            }
        },
        plugins: {
            'hapi-swagger': {
                response: {
                    '200': {
                        description: 'success',
                        schema: joi.object({
                            name: joi.string().description("返回用户名字")
                        })
                    },
                    '400': {
                        description: "请求值错误"
                    }
                }
            }
        },
        tags: ['api'],
        notes: '返回一个名字',
        description: "传入一个名字"
    }
})
server.route(require("./router/CreateUser"))
server.route(require("./router/upload"))
init();